#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
# new Env("三福会员")
# cron: 40 8 * * *
✦ 小程序信息    ▸ 名称：三福会员中心
▸ 类别：积分换实物
▸ 可换种类：各品牌权益（5000积分兑腾讯视频会员-需抢购）
✦ 执行说明    ▸ 首次执行无需手动进入小程序【无需手机号绑定】
▸ 每日自动执行签到任务
"""
import time
import json
import os
import requests
from typing import Optional, Dict
from requests.exceptions import RequestException

class SanfuSignin:
    def __init__(self):
        self.base_url = "https://crm.sanfu.com"
        self.app_id = "wxfe13a2a5df88b058"
        self.client = requests.Session()
        self.headers = {
            "Host": "crm.sanfu.com",
            "Connection": "keep-alive",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B)",
            "Content-Type": "application/json",
            "Accept": "*/*",
            "Referer": "https://servicewechat.com/wxfe13a2a5df88b058/333/page-frame.html",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9"
        }
        self.sid = None
        
        # 协议服务配置
        proxy = os.getenv("API_PROXY", "192.168.0.183:5000").strip()
        if not proxy.startswith(("http://", "https://")):
            proxy = f"http://{proxy}"
        self.local_proxy = proxy
        self.retry_times = 3

    def get_wx_list(self):
        """获取微信账户列表"""
        url = f"{self.local_proxy}/getallwx"
        try:
            response = requests.get(url, timeout=10)
            if response.status_code == 200:
                return response.json()
            print(f"获取微信列表失败: HTTP {response.status_code}")
        except RequestException as e:
            print(f"获取微信列表失败: {str(e)}")
        return []

    def get_wx_code(self, wxid: str) -> Optional[str]:
        """获取小程序登录凭证"""
        url = f"{self.local_proxy}/loginbyapp?Wxid={wxid}&appid={self.app_id}"
        try:
            response = requests.get(url, timeout=10)
            if response.status_code == 200:
                return response.json().get("code")
            print(f"获取wxCode失败: HTTP {response.status_code}")
        except RequestException as e:
            print(f"获取wxCode失败: {str(e)}")
        return None

    def login(self, wxid: str) -> bool:
        """用户登录"""
        code = self.get_wx_code(wxid)
        if not code:
            print("获取微信登录code失败")
            return False

        payload = {
            "code": code,
            "appid": self.app_id,
            "shoId": "",
            "userId": "",
            "sourceWxsceneid": 1145,
            "sourceUrl": "pages/ucenter_index/ucenter_index"
        }
        
        url = f"{self.base_url}/ms-sanfu-wechat-customer-core/customer/core/wxMiniAppLogin"
        
        try:
            response = self.client.post(url, json=payload, headers=self.headers, timeout=15)
            data = response.json()
            
            if data.get("code") == 200 and data.get("success"):
                sid = data.get("data", {}).get("sid")
                if sid:
                    self.sid = sid
                    print("登录成功")
                    return True
                print("登录失败：未获取到sid")
            else:
                print(f"登录失败：{data.get('msg', '未知错误')}")
        except Exception as e:
            print(f"登录请求失败: {e}")
        return False

    def check_signin_status(self) -> Optional[bool]:
        """检查签到状态"""
        if not self.sid:
            print("未获取到sid，无法检查签到状态")
            return None
        
        url = f"{self.base_url}/ms-sanfu-wechat-customer/customer/index/equity?sid={self.sid}"
        
        try:
            response = self.client.get(url, headers=self.headers, timeout=15)
            data = response.json()
            
            if data.get('code') == 200:
                sign_in = data.get('data', {}).get('signIn', 1)
                is_signed = sign_in == 1
                print(f"签到状态: {'已签到' if is_signed else '未签到'}")
                return is_signed
            print(f"检查签到状态失败：{data.get('msg', '未知错误')}")
        except Exception as e:
            print(f"检查签到状态请求失败: {e}")
        return None

    def submit_signin(self) -> Optional[Dict]:
        """提交签到"""
        if not self.sid:
            print("未获取到sid，无法签到")
            return None
        
        payload = {
            "sid": self.sid,
            "signWay": 0
        }
        
        url = f"{self.base_url}/ms-sanfu-wechat-common/customer/onSign"
        
        try:
            response = self.client.post(url, json=payload, headers=self.headers, timeout=15)
            data = response.json()
            
            if data.get('code') == 200:
                return data.get('data', {})
            print(f"签到失败：{data.get('msg', '未知错误')}")
        except Exception as e:
            print(f"签到请求失败: {e}")
        return None

    def get_account_info(self) -> Optional[Dict]:
        """获取账号基本信息"""
        if not self.sid:
            print("未获取到sid，无法获取账号信息")
            return None
        
        url = f"{self.base_url}/ms-sanfu-wechat-customer/customer/index/baseInfo?sid={self.sid}"
        
        try:
            response = self.client.get(url, headers=self.headers, timeout=15)
            data = response.json()
            
            if data.get('code') == 200:
                return data.get('data', {})
            print(f"获取账号信息失败：{data.get('msg', '未知错误')}")
        except Exception as e:
            print(f"获取账号信息请求失败: {e}")
        return None

    def process_account(self, wx_account: dict) -> bool:
        """处理单个账号"""
        wxid = wx_account.get("Wxid")
        wxname = wx_account.get("wxname", "未知用户")
        print(f"\n处理账号: {wxname}")

        if not self.login(wxid):
            print(f"{wxname} 登录失败")
            return False

        sign_status = self.check_signin_status()
        if sign_status is None:
            print(f"{wxname} 检查签到状态失败")
            return False

        if not sign_status:
            sign_result = self.submit_signin()
            if sign_result is None:
                print(f"{wxname} 签到失败")
                return False
            
            # 处理签到结果
            fubi = sign_result.get('fubi', 0)
            keep_days = sign_result.get('onKeepSignDay', 0)
            gift_days = sign_result.get('giftMoneyDaily', 0)
            
            print(f"签到成功，获得{fubi}个福币，连续签到{keep_days}天")
            if gift_days > 0:
                print(f"再签{gift_days}天可得神秘礼物🎁")

        # 获取账号信息
        account_info = self.get_account_info()
        if account_info:
            cus_id = account_info.get('curCusId', '未知ID')
            total_fubi = account_info.get('fubi', 0)
            print(f"账号ID: {cus_id}，当前有{total_fubi}个福币")
        
        return True

def main():
    print("="*50)
    print("三福小程序签到 - 协议版")
    print("="*50)
    
    signin = SanfuSignin()
    print(f"协议服务地址: {signin.local_proxy}")
    
    wx_accounts = signin.get_wx_list()
    if not wx_accounts:
        print("未获取到任何在线账号")
        return

    print(f"获取到 {len(wx_accounts)} 个账号")
    
    for i, account in enumerate(wx_accounts, 1):
        print(f"\n{'='*50}")
        print(f"处理第 {i}/{len(wx_accounts)} 个账号: {account.get('wxname')}")
        try:
            signin.process_account(account)
        except Exception as e:
            print(f"处理账号时发生错误: {e}")
        
        if i < len(wx_accounts):
            print("等待2秒...")
            time.sleep(2)
    
    print("\n所有账号处理完成")

if __name__ == "__main__":
    main()